package io;

import util.Point;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

import main.Constants;
import main.Game;

import objects.Asteroid;

import ship.Ship;

public class LevelLoader {
	public static void loadLevel(String filename) {
		try {
			BufferedReader b = new BufferedReader(new FileReader(filename));
			String line;
			while((line = b.readLine()) != null) {
				StringTokenizer tok = new StringTokenizer(line, " ");
				while(tok.hasMoreTokens()) {
					String type = tok.nextToken();
					if(type.equals("Ship")) {
						double player = Double.parseDouble(tok.nextToken());
						double startX = Double.parseDouble(tok.nextToken());
						double startY = Double.parseDouble(tok.nextToken());
						Game.game.registerShip(new Ship(new Point(startX, startY), (int) player), Constants.MOVE | Constants.DRAW | Constants.COLLIDE);
					}
					if(type.equals("Asteroid")) {
						double startX = Double.parseDouble(tok.nextToken());
						double startY = Double.parseDouble(tok.nextToken());
						double xRad = Double.parseDouble(tok.nextToken());
						double yRad = Double.parseDouble(tok.nextToken());
						Game.game.registerAll(new Asteroid(new Point(startX, startY), (int) xRad, (int) yRad));
					}
				}
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static Ship getShip(String filename, int playerTarget) {
		try {
			BufferedReader b = new BufferedReader(new FileReader(filename));
			String line;
			while((line = b.readLine()) != null) {
				StringTokenizer tok = new StringTokenizer(line, " ");
				while(tok.hasMoreTokens()) {
					String type = tok.nextToken();
					if(type.equals("Ship")) {
						double player = Double.parseDouble(tok.nextToken());
						double startX = Double.parseDouble(tok.nextToken());
						double startY = Double.parseDouble(tok.nextToken());
						if(player == playerTarget) {
							return new Ship(new Point(startX, startY), (int) player);
						}
					}
					
				}
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
